package com.company.finance.ddd.domain.core.voucher.repository;

import com.company.finance.ddd.common.IRepository;
import com.company.finance.ddd.domain.core.voucher.aggregate.Voucher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.lang.reflect.Field;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 *
 * @author wanglei
 * @version $$Id: AccountingDocumentRepository, v 0.1 2021/2/5 15:10 wanglei Exp $$
 */
@Repository
public class VoucherItemRepository implements IRepository<Voucher.VoucherItem> {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public void save(Voucher.VoucherItem voucherItem) {
        String sql = "insert into accounting_document_item ({0}) values ({1})";

        List<Object[]> batchParams = new ArrayList<>();

        StringBuilder columns = new StringBuilder();
        StringBuilder valuePlaceholder = new StringBuilder();
        //Build sql column and placeholder
        List<Object> params = new ArrayList<>();
        for (Field field : voucherItem.getClass().getDeclaredFields()) {
            field.setAccessible(true);
            Object fieldValue;
            try {
                fieldValue = field.get(voucherItem);
            } catch (IllegalAccessException e) {
                throw new RuntimeException(e);
            }
            if (null != fieldValue) {
                columns.append(field.getName()).append(", ");
                valuePlaceholder.append("?").append(", ");
                params.add(fieldValue);
            }
        }
        batchParams.add(params.toArray());
        jdbcTemplate.update(MessageFormat.format(sql, columns.delete(columns.length() - 2, columns.length()).toString()
                , valuePlaceholder.delete(valuePlaceholder.length() - 2, valuePlaceholder.length()).toString()), batchParams);
    }

    @Override
    public List<Voucher.VoucherItem> query(Map<String, Object> queryCondition) {
        Object[] param = {queryCondition.get("voucher_id")};
        return jdbcTemplate.query("select * from accounting_document_item where voucher_id = ?"
                , param, new BeanPropertyRowMapper<>(Voucher.VoucherItem.class));
    }

    @Override
    public Voucher.VoucherItem get(Long voucherId) {
        return null;
    }

    @Override
    public void delete(Long billId) {
        Long[] param = {billId};
        Long voucherId = jdbcTemplate.queryForObject("select id from accounting_document where bill_id = ?", param, Long.class);
        jdbcTemplate.update("delete from accounting_document where bill_id = ?", billId);
        jdbcTemplate.update("delete from accounting_document_item where voucher_id = ?", voucherId);
    }
}
